package org.zerg.service.impl;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.zerg.dao.UserDao;
import org.zerg.dao.cache.RedisTokenDao;
import org.zerg.dto.AnotherFileDto;
import org.zerg.dto.FileDto;
import org.zerg.entity.User;
import org.zerg.exception.TokenException;

@Service
public class BaseServiceImpl {

	@Autowired
	private UserDao userDao;
	
	@Value("${adImage.url}")
	private String adImageUrl;
	
	@Value("${adImage.savePath}")
	private String savePath;
	
	@Autowired
	private RedisTokenDao redisTokenDao;
	
	public User getUserByToken(String token){
		if(token==null){
			return null;
		}
		User user = redisTokenDao.fromTokenGetUser(token);
		return user;
	}
	
	
	//获取随机时间--分秒
	protected String getRandomTime() {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("mmss");
		String str = sdf.format(date);
		return str;
	}
	
	//获取订单创建时间
	protected String getHTime() {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时");
		String str = sdf.format(date);
		return str;
	}

	//获取当前时间--年月日
	public String getNowTime(){
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String str = sdf.format(date);
		return str;
	}
	
	//保存图片
	public String saveFile(FileDto dto){
		String fileName = System.currentTimeMillis()+"_"+dto.getImgFile().getOriginalFilename();
		if(dto.getImgFile()!=null&&dto.getImgFile().getSize()>0){
		File file = new File(savePath+fileName);
		File fileFolder = new File(savePath);
		if(fileFolder.exists()){
			fileFolder.mkdirs();
		}
		try {
			dto.getImgFile().transferTo(file);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		}
		return fileName;
	}
	
	//保存图片（另一张图片）
	public String saveAnotherFile(AnotherFileDto andto){
		String fileName = System.currentTimeMillis()+"_"+andto.getImgFile2().getOriginalFilename();
		if(andto.getImgFile2()!=null&&andto.getImgFile2().getSize()>0){
		File file = new File(savePath+fileName);
		File fileFolder = new File(savePath);
		if(fileFolder.exists()){
			fileFolder.mkdirs();
		}
		try {
			andto.getImgFile2().transferTo(file);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		}
		return fileName;
	}
	
}
